package com.sisgh.jefdv1.cmd.command.has.one;

import com.sisgh.jefdv1.cmd.command.has.ArgsCommand;
import com.sisgh.jefdv1.cmd.command.has.arg.argument.Argument;
import com.sisgh.jefdv1.exception.cmd.InvalidCommandException;
import com.sisgh.jefdv1.exception.cmd.arg.InvalidArgumentException;
import com.sisgh.jefdv1.util.StringUtils;

import java.util.List;

public abstract class OneArgCommand extends ArgsCommand {

    protected Argument arg;

    protected void doProcessArg(Argument arg, List<String> args) {
        String argName = args.get(0);
        if (!arg.matches(argName)) {
            arg.values(args);
            return;
        }

        List<String> res = args.subList(1, args.size());

        if (res.isEmpty()) {
            return;
        }

        arg.values(res);
    }

    @Override
    protected void processArgs(List<String> parts) throws InvalidArgumentException {
        if (parts.isEmpty()) {
            throw new InvalidCommandException("至少1个参数");
        }

        doProcessArg(this.arg, parts);

        // 没有值 && 没有默认值
        if (!this.arg.hasValues() && arg.valueRequired()) {
            String msg = StringUtils.format("参数[{}/{}]需要参数值", this.arg.longName(), this.arg.shortName());
            throw new InvalidArgumentException(msg);
        }
    }

    public OneArgCommand(Argument arg) {
        this.arg = arg;
    }
}
